<template>
  <div  class="app-container">
    <!--选择仓库-->
    <SelectXProperty ref="openSelectXProperty"  @propertyXSelected="propertyXSelected"></SelectXProperty>
    <SelectOProperty ref="openSelectOProperty"  @propertyOSelected="propertyOSelected"></SelectOProperty>
    <SelectPropertyWarehouse ref="openSelectPropertyWarehouse" @propertyWarehouseSelected="propertyWarehouseSelected"></SelectPropertyWarehouse>
     <!-- 货权转移 -->
     <div class="detail-title-box">
      <span>详情信息</span>
    </div>
      <el-form ref="ruleForm" :model="ruleForm" label-width="150px" :inline="true" :rules="rules">
        <el-form-item label="新货权人" prop="khmc" :rules="rules.khmc">
          <el-input
              v-model="ruleForm.khmc"
              :disabled="true"
              style="width:225px"
          >
            <el-button slot="append" @click="propertyXSelect">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="旧货权人" prop="khmc0" :rules="rules.ckcw">
          <el-input
              v-model="ruleForm.khmc0"
              :disabled="true"
              style="width:225px"
          >
            <el-button slot="append" @click="propertyOSelect">选择</el-button>
          </el-input>
        </el-form-item>
        <el-form-item label="货权费用方" prop="hqf">
           <el-select
            v-model="ruleForm.hqf"
            placeholder="请选择货权费用方"
            clearable
          >
            <el-option
                v-for="(item, index) in PropertyType"
                :key="index"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="dzbz">
          <el-input
            v-model="ruleForm.dzbz"
            placeholder="请输入备注"
            clearable
          />
        </el-form-item>
        <el-row class="mt20">
          <el-col :span="6">
            <el-form-item label="锁仓线:" prop="scx">
              {{showData.scx}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="提示金额:" prop="tsje">
              {{showData.tsje}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="本次提货金额:" prop="thje">
              {{getThje}}
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="所有货物剩余金额:" prop="hwje">
              {{showData.hwje}}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" plain size="mini" @click="warehouseSelect">选择库存</el-button>
              <el-button type="primary" plain size="mini" @click="handleRefresh">刷新</el-button>
            </el-col>
        </el-row>
        <el-table
          :data="ruleForm.inp"
          class="form-table"
        >
        <af-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleRowDelete(scope.$index)"
            >删 除</el-button>
          </template>
        </af-table-column>
        <af-table-column label="物品规格" align="center" prop="spzs" width="150">
          <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.spzs" size="mini" placeholder="请输入物品规格"/>
            </el-form-item>
          </template>
        </af-table-column>
        <af-table-column label="批号" align="center" prop="spbh" width="150">
          <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.spbh" size="mini" placeholder="请输入批号"/>
            </el-form-item>
          </template>
        </af-table-column>
        <af-table-column label="柜号" align="center" prop="spgh" width="150">
          <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.spgh" size="mini" placeholder="请输入批号"/>
            </el-form-item>
          </template>
        </af-table-column>
        <af-table-column label="结存件数" align="center" prop="spjs2" width="150"/>
        <af-table-column label="货转件数" align="center" prop="spjs" width="150">
           <template slot-scope="scope">
            <el-form-item :prop="'inp.' + scope.$index + '.spjs'" :rules="rules.inp.spjs">
              <el-input v-model="scope.row.spjs" size="mini" placeholder="请输入货转件数" @input="getWeight(scope.$index)" type="number" min="0"/>
            </el-form-item>
          </template>
        </af-table-column>
        <af-table-column label="单重(KG)" align="center" prop="spjsl" width="150"/>
        <af-table-column label="货转吨数" align="center" prop="spsl" width="150"/>
        <af-table-column label="所有者" align="center" prop="spkhmc" width="150"/>
        <af-table-column label="所在系统" align="center" prop="khlx" width="150"/>
        <af-table-column label="原入仓日期" align="center" prop="ssrqid" width="150"/>
        <af-table-column label="货转日期" align="center" prop="ssrqidn" width="150" >
          <template slot-scope="scope">
              <el-form-item :prop="'inp.' + scope.$index + '.ssrqidn'" :rules="rules.inp.ssrqidn">
                <el-date-picker
                  v-model="scope.row.ssrqidn"
                  default-value
                  value-format="yyyy-MM-dd"
                  type="date"
                  placeholder="请选择货转日期"
                  style="width:90%"
                  size="mini">
                </el-date-picker>
              </el-form-item>
            </template>
        </af-table-column>
        <af-table-column label="天数" align="center" prop="days" width="150"/>
        <af-table-column label="品牌" align="center" prop="spcd" width="150">
           <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.spcd" size="mini" placeholder="请输入品牌"/>
            </el-form-item>
          </template>
        </af-table-column>
        <af-table-column label="用户条码" align="center" prop="sptm" width="150"/>
        <af-table-column label="仓库条码" align="center" prop="sptmc" width="150"/>
        <af-table-column label="仓库" align="center" prop="spckmc" width="150"/>
        <af-table-column label="仓位" align="center" prop="ckcw" width="150"/>
        <af-table-column label="估值单价" align="center" prop="spdj" width="150"/>
        <af-table-column label="估值金额" align="center" prop="spje" width="150"/>
        <af-table-column label="备注" align="center" prop="itbz" width="150" >
           <template slot-scope="scope">
            <el-form-item>
              <el-input v-model="scope.row.itbz" size="mini" placeholder="请输入备注"/>
            </el-form-item>
          </template>
        </af-table-column>
        </el-table>
        <el-row class="mt20" :gutter="20">
          <el-form-item label="件数">{{amountTotal}}</el-form-item>
          <el-form-item label="重量(吨)">{{weightTotal}}</el-form-item>
        </el-row>
      </el-form>
      <el-row type="flex" justify="center" :gutter="5" class="mt20">
        <el-col :span="1.5">
          <el-button type="primary" @click="warehousePropertySubmit('ruleForm')" v-hasPermi="['zhcloud:hqzy:add']">提交货权转移</el-button>
        </el-col>
         <el-col :span="1.5">
          <el-button @click="goBack">返回</el-button>
        </el-col>
      </el-row>
  </div>
</template>

<script>
import { warehousePropertyAdd, warehousePropertyDetailRefresh } from "@/api/storage/commonGoods/warehouseProperty"
import SelectXProperty from './selectXProperty.vue'
import SelectOProperty from './selectOProperty.vue'
import SelectPropertyWarehouse from './selectPropertyWarehouse.vue'
import { WEIGHT_DIGIT, NUMBER_DIDGIT, AMOUNT_DIGIT } from '@/utils/constant'
import { calculateDays } from '@/utils'

export default {
  name: "WarehousePropertyMove",
  components: { SelectXProperty, SelectOProperty, SelectPropertyWarehouse },
  data() {
    return {
      // 显示搜索条件
      showSearch: true,
      //货权配用方
      PropertyType:[
        {label:"旧货权方", value:"旧货权方"},
        {label:"新货权方", value:"新货权方"},
        {label:"免收费用", value:"免收费用"},
      ],
      //刷新参数
      refreshQuery: {
        khid:""
      },
       //显示数据
      showData:{
        scx: 0,
        tsje: 0,
        thje: 0,
        hwje: 0
      },
      //选择明细仓位参数
      selectPositonQuery:{
        spckid:""
      },
      //添加详情
      ruleForm:{
        dzbz: "",
        dzid: 0,
        hqf: "旧货权方",
        inp: [],
        khlx: "商城",
        khmc: "",
        khmc0: "",
        khmcid: "",
        khmcid0: ""
      },
      //校验
      rules: {
        khmc:[{
          required: true,
          message: '新货权方不能为空',
          trigger: "blur"
        }],
        khmc0:[{
          required: true,
          message: '旧货权方不能为空',
          trigger: "blur"
        }],
        inp:{
          spjs: [
            {
              required: true,
              message: '货转件数不能为空',
              trigger: "blur"
            },
            {
              required: true,
              validator: this.checkSpjs,
              trigger: "blur"
            }
          ],
          ssrqidn: [
            {
              required: true,
              message: '转货日期不能为空',
              trigger: "blur"
            },
            {
              required: true,
              validator: this.checkSsrqidn,
              trigger: "blur"
            }
          ]
        }
      }
    };
  },
  computed: {
    amountTotal() {
      let sum = 0
      const inp = this.ruleForm.inp
      for(let i in inp) {
        if(inp[i].spjs) {
          sum += parseFloat(inp[i].spjs)
        }
      }
      return parseFloat(sum.toFixed(NUMBER_DIDGIT))
    },
    weightTotal() {
      let sum = 0
      const inp = this.ruleForm.inp
      for(let i in inp) {
        if(inp[i].spsl) {
          sum += parseFloat(inp[i].spsl)
        }
      }
      return parseFloat(sum.toFixed(WEIGHT_DIGIT))
    },
    getThje() {
      this.showData.thje  = this.deliveryAmount()
      return this.showData.thje 
    }
  },
  methods: {
    /**计算重量 */
    getWeight(index) {
      const r = this.ruleForm.inp[index]
      let spjs = r.spjs
      let spjsl = r.spjsl
      if(spjs.indexOf('.')>0){
        spjs=spjs.slice(0,spjs.indexOf('.')+4)
      }      
      r.spjs = spjs
      r.spsl = parseFloat((spjs*spjsl/1000).toFixed(WEIGHT_DIGIT))
      r.spje = parseFloat(r.spsl*r.spdj).toFixed(AMOUNT_DIGIT)
    },
    /**提交货权转移 */
    addWarehouseProperty() {
      this.$modal.loading("数据正在执行中，请稍等...")
      warehousePropertyAdd(this.ruleForm).then(response => {
        this.$modal.closeLoading()
        this.$modal.msgSuccess('执行成功')
        this.goWarehouseProperty()
      }).catch(()=> {
        this.$modal.closeLoading()
      })
    },
    /** 提交货权转移提交*/
    warehousePropertySubmit(formName) {
      this.$refs[formName].validate((valid, data) => {
        if(valid) {
          if(this.ruleForm.inp.length > 100) return this.$modal.msgError("货物行数不能大于100行！")
          if(this.ruleForm.inp.length === 0) return this.$modal.msgError("请先输入数据！")

          if(parseFloat(this.showData.thje) == 0) {
            this.$modal.confirm("提交前请确保信息正确！是否确认提交？").then(()=> {
                this.addWarehouseProperty()
              }).catch(() => {})
          } else if(this.showData.thje > 0) {
            if(this.showData.hwje - this.showData.thje > this.showData.tsje) {
              this.$modal.confirm("提交前请确保信息正确！是否确认提交？").then(()=> {
                this.addWarehouseProperty()
              }).catch(() => {})
            } else if(this.showData.hwje - this.showData.thje <= this.showData.tsje && this.showData.hwje - this.showData.thje >= this.showData.scx) {
              this.$modal.confirm("本次转货后，剩余货值小于提示金额，是否继续办理转货？").then(() => {
                this.addWarehouseProperty()
              }).catch(()=> {})
            } else if(this.showData.hwje - this.showData.thje < this.showData.scx) {
              this.$modal.confirm("本次转货后，剩余货值小于锁仓金额，暂不能转货！请联系业务处理。")
            }
          } else {
            this.$modal.msgError("无法出仓，请联系管理员")
          }
        } else {
          for(let i in data) {
            const item = data[i]
            for(let j in item) {
              const message = item[j].message
              return this.$modal.msgError(message)
            }
          }
          return false
        }
      })
    },
    /** 添加行删除*/
    handleRowDelete(index) {
      this.ruleForm.inp.splice(index, 1)
    },
    /**本次提货金额计算 */
    deliveryAmount() {
      const inp = this.ruleForm.inp
      let num = 0
      for(let i in inp) {
        if(!inp[i].spje) {
          num += 0
        } else {
          num += parseFloat(inp[i].spje)
        }
      }
      return parseFloat(num).toFixed(AMOUNT_DIGIT)
    },
    /**选择新货权人 */
    propertyXSelect() {
      this.$refs.openSelectXProperty.open()
    },
    /**选择仓库 */
    warehouseSelect() {
      if(!this.ruleForm.khmc0) return this.$modal.msgError("请先选择旧货权人！")
      const inp = this.ruleForm.inp
      this.$refs.openSelectPropertyWarehouse.open(inp,this.ruleForm.khmcid0)
    },
    /**选择旧货权人 */
    propertyOSelect() {
      if(!this.ruleForm.khmc) return this.$modal.msgError("请先选择新货权人！")
      this.$refs.openSelectOProperty.open(this.ruleForm.khmc)
    },
    /**选择仓库返回 */
    propertyWarehouseSelected(data) { 
      if(data.length > 0) {
        for(let i in data) {
          this.ruleForm.inp.push(data[i])
        }
      }
      this.showData.thje = this.deliveryAmount() 
      this.detailRefresh()
    },
    /**选择新货权人返回 */
    propertyXSelected(data) {
      this.ruleForm.khmc = data.khmc
      this.ruleForm.khmcid = data.khid
    },
    /**选择旧货权人返回 */
    propertyOSelected(data) {
      this.ruleForm = {
        ...this.ruleForm,
        khmc0: data.spkhmc,
        khmcid0: data.spkhmcid,
        khlx: data.khlx,
        inp:data.inp
      }
      this.refreshQuery.khid = data.spkhmcid
      this.showData = {
        ...this.showData,
        scx:data.scx,
        tsje:data.tsje,
        hwje:data.hwje,
        thje:this.deliveryAmount()
      }
      this.detailRefresh()
    },
    /**验证出货件数 */
    checkSpjs(rule, value, callback) {
      const a = rule.field.split('.')
      const index = a[1]
      const spjs2 = parseFloat(this.ruleForm.inp[index].spjs2)
      if(spjs2 < value) {
        callback("货转件数不可超过结存件数")
      } else {
        callback()
      }
    },
    /**验证转货日期 */
    checkSsrqidn(rule, value, callback) {
      const a = rule.field.split('.')
      const index = a[1]
      const currentInp = this.ruleForm.inp[index]
      const warehouseOutDate = currentInp.ssrqidn
      const warehouseInDate = currentInp.ssrqid
      //同一天算1天
      const days = calculateDays(warehouseInDate, warehouseOutDate) + 1
      this.ruleForm.inp[index].days = days
      if(days < 1) {
        callback("转货日期不能早于原入仓日期！")
      } else {
        callback()
      }
    },
    /**刷新 */
    detailRefresh() {
      this.$modal.loading("数据正在刷新中，请稍等...")
      warehousePropertyDetailRefresh(this.refreshQuery).then(response => {
        this.$modal.closeLoading()
        const data = response.data
        this.showData = {
          scx :data.scx,
          tsje :data.tsje, 
          hwje :data.hwje
        }
      }).catch(()=> {
        this.$modal.closeLoading()
      })
    },
    /**点击刷新 */
    handleRefresh() {
      if(!this.ruleForm.khmc0) return this.$modal.msgError("请先选择旧货权人！")
      this.detailRefresh()
    },
    //跳回货物转移页
    goWarehouseProperty() {
      this.$tab.closePage(this.$route)
      this.$router.push({name:"WarehouseProperty", params:{refresh:true}})
    },
    /**返回不刷新 */
    goBack() {
      this.$tab.closePage()
      this.$router.go(-1)
    }
  }
};
</script>
